package cn.woniu.ecommerceplatform.util;

import com.nimbusds.jose.*;
import com.nimbusds.jose.crypto.MACSigner;
import com.nimbusds.jose.crypto.MACVerifier;

import java.text.ParseException;
import java.util.HashMap;
import java.util.Map;

/**
 * JWT加密工具类
 * 1、创建jwt加密
 * 2、校验jwt是否合法
 * 3、返回载荷部分
 */
public class JWTUtil {

    private static final String key="fdjskf;ldfi3w9930 8kl8kikkdskfkmahdksjalhfuidshakjfhdkslahjfkdksljahfdskjlajkofasik";

    /**
     * 创建JWT加密
     * @param map 用户信息的map集合
     * @return 加密后的字符串
     * @throws JOSEException
     */
    public static String createJWT(Map<String,Object> map) throws JOSEException {
        //创建JWT头部
        JWSHeader jwsHeader = new JWSHeader.Builder(JWSAlgorithm.HS256).type(JOSEObjectType.JWT).build();
        //创建载荷
        Payload payload = new Payload(map);

        JWSObject jwsObject=new JWSObject(jwsHeader,payload);
        //加载签名信息
        JWSSigner jwsSigner=new MACSigner(key);
        jwsObject.sign(jwsSigner);
        return jwsObject.serialize();
    }
    public static String createJWT(String username) throws JOSEException {
        //创建JWT头部
        JWSHeader jwsHeader = new JWSHeader.Builder(JWSAlgorithm.HS256).type(JOSEObjectType.JWT).build();
        Map<String,Object> map=new HashMap<>();
        map.put("username",username);
        //创建载荷
        Payload payload = new Payload(map);

        JWSObject jwsObject=new JWSObject(jwsHeader,payload);
        //加载签名信息
        JWSSigner jwsSigner=new MACSigner(key);
        jwsObject.sign(jwsSigner);
        return jwsObject.serialize();
    }

    /**
     * 校验是否合法
     * @param jwt jwt字符串
     * @return 是否合法
     * @throws ParseException 解析异常
     * @throws JOSEException JOSE
     */
    public static boolean checkJWT(String jwt) throws ParseException, JOSEException {
        JWSObject jwsObject = JWSObject.parse(jwt);
        JWSVerifier jwsVerifier=new MACVerifier(key);
        return jwsObject.verify(jwsVerifier);
    }

    /**
     * 解析JWT加密串
     * @param jwt jwt串
     * @return 用户信息的map集合
     * @throws ParseException 解析异常
     */
    public static Map<String,Object> parseMap(String jwt) throws ParseException {
        JWSObject jwsObject=JWSObject.parse(jwt);
        return jwsObject.getPayload().toJSONObject();
    }

    public static String parseUsername(String jwt) throws ParseException {
        JWSObject jwsObject=JWSObject.parse(jwt);
        Map<String, Object> map = jwsObject.getPayload().toJSONObject();
        return (String) map.get("username");
    }


}
